package cn.modfun.common.third;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.UUID;

import org.apache.log4j.Logger;

import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import cn.modfun.common.lang.Array;
import cn.modfun.common.path.PathUtils;
import cn.modfun.common.system.OSInfo;
/**
 * 
 * @author LinCH
 *
 */
public class PhantomJSUtils {

	private static Logger logger = Logger.getLogger(PhantomJSUtils.class);
	/**
	 * 定义默认程序名
	 */
	public static String PROGRAM = "phantomjs.exe";
	/**
	 * 定义默认程序路径
	 */
	public static String PROGRAM_FOLDER = PathUtils.getWebRoot()+"WEB-INF/plugins/phantomjs/";
	
	/**
	 * 定义highchart对象
	 */
	public static HighCharts highCharts = null;

	static{
		if(OSInfo.isLinux()){
			PROGRAM = "phantomjs";
		}
		Setting setting = null;
		String highcharts_convertjs_path = null,highcharts_resource_folder = null;
		File file = new File(new ClassPathResource("/").getUrl()+"/config/phan");
		if(file!=null && file.exists()){
			setting = new Setting("config/phantomjs.txt");
			if(StrUtil.isNotBlank(setting.getByGroup("PROGRAM_FOLDER", "core"))){
				PROGRAM_FOLDER = setting.getByGroup("PROGRAM_FOLDER", "core");
			}
			if(StrUtil.isNotBlank(setting.getByGroup("CONVERTJS_PATH", "highcharts"))){
				highcharts_convertjs_path = setting.getByGroup("CONVERTJS_PATH", "highcharts");
			}
			if(StrUtil.isNotBlank(setting.getByGroup("RESOURCE_FOLDER", "highcharts"))){
				highcharts_resource_folder = setting.getByGroup("RESOURCE_FOLDER", "highcharts");
			}
		}
		highCharts = new HighCharts(highcharts_convertjs_path,highcharts_resource_folder);
	}
	
	/**
	 * 定义highchart内部类
	 * @author LinCH
	 *
	 */
	public static class HighCharts{
		/**
		 * 转换文件的路径
		 */
		private String convertjs_path = PathUtils.getWebRoot()+"WEB-INF/plugins/phantomjs/highcharts/highcharts-convert.js";
		/**
		 * 资源的目录
		 */
		private String resource_folder = PathUtils.getWebRoot()+"WEB-INF/plugins/phantomjs/highcharts/";
		/**
		 * 指向的highcharts资源文件
		 */
		private String resources = "";
		/**
		 * 临时目录
		 */
		private String resources_template_path = resource_folder+"/temp/";
		
		public HighCharts(){}
		
		public HighCharts(String convertjsPath,String resourceFolder){
			this.convertjs_path = convertjsPath == null ? convertjs_path : convertjsPath;
			this.resource_folder = resourceFolder == null ? resource_folder : resourceFolder;
		}
		/**
		 * 初始化参数
		 */
		public void init(){
			Array _resources = new Array();
			File _resource_folder = new File(resource_folder);
			if(_resource_folder!=null && _resource_folder.isDirectory()){
				ArrayList<File> files = new ArrayList<File>(Arrays.asList(_resource_folder.listFiles()));
				Collections.sort(files, new Comparator<File>() {
				    @Override
				    public int compare(File o1, File o2) {
				        if (o1.isDirectory() && o2.isFile())
				            return -1;
				        if (o1.isFile() && o2.isDirectory())
				            return 1;
				        return o2.getName().compareTo(o1.getName());
				    }
				});
				for(File file : files){
					if(file.isFile()&&!"highcharts-convert.js".equals(file.getName())){
						_resources.push(resource_folder,file.getName());
					}
				}
			}
			this.resources = _resources.join();
		}
		/**
		 * 转换
		 * @param template_path	模板路径
		 * @param target_path	生成目标所在路径
		 */
		@SuppressWarnings("unused")
		public void convert(String template_path,String target_path){
			init();
			/**
			 * 执行转换
			 */
			Runtime rt = Runtime.getRuntime();
			Process p = null;  
			try {  
				String cmd = new Array().push(PhantomJSUtils.PROGRAM_FOLDER+PhantomJSUtils.PROGRAM).push(convertjs_path).push("-infile").push(template_path).push("-outfile").push(target_path).push("-resources ",resources).join(" ");
				logger.debug(cmd);
				p = rt.exec(cmd);  
			} catch (Exception e) {  
			    e.printStackTrace();
			}
		}
		/**
		 * 通过json内容进行生成临时文件，然后通过临时文件再生成文件
		 * @param content
		 * @param target_path
		 */
		public void convertByContent(String content,String target_path){
			init();
			/* 把内容生成临时文件 */
			String temp_file = resources_template_path+UUID.randomUUID().toString().replace("-", "")+".json";
			FileWriter writer = new FileWriter(temp_file);
			writer.write(content);
			/**/
			convert(temp_file,target_path);
		}
	}
	public static void main(String[] args) {
//		HighCharts hc = new HighCharts();
//		hc.convert(PathUtils.getWebRoot()+"WEB-INF/plugins/phantomjs/tpl.json", PathUtils.getWebRoot()+"b.jpg");
		String template_path = PathUtils.getWebRoot()+"WEB-INF/plugins/phantomjs/tpl.json";
		String target_path = PathUtils.getWebRoot()+"d.jpg";
		PhantomJSUtils.highCharts.convert(template_path, target_path);
	}
	
}
